<template>
  <Dialog
    v-if="dialogVisible"
    v-model="dialogVisible"
    :maxHeight="'800px'"
    width="80%"
    title="选择商品"
    :before-close="() => closeDialog()"
    class="mobile-dialog"
  >
    <!--    顶部查询项-->
    <el-form :model="form" inline class="mobile-form">
      <el-form-item :label="t('wholesalOrder.productName')">
        <el-input
          v-model="form.product"
          clearable
          :placeholder="t('wholesalOrder.productName')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('wholesalOrder.warehouse')">
        <el-select
          v-model="form.wid"
          :placeholder="t('wholesalOrder.warehouse')"
          clearable
          filterable
          style="width: 250px"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('wholesalOrder.brand')">
        <el-select
          v-model="form.brand"
          :placeholder="t('wholesalOrder.brand')"
          clearable
          style="width: 180px"
        >
          <el-option
            v-for="item in brandList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('wholesalOrder.type')">
        <el-select
          v-model="form.is_futures"
          :placeholder="t('wholesalOrder.type')"
          clearable
          style="width: 250px"
        >
          <el-option
            v-for="item in warehouseTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('wholesalOrder.arrivalDate')">
        <el-date-picker
          v-model="form.date"
          type="daterange"
          range-separator="-"
          start-placeholder="起始时间"
          end-placeholder="结束时间"
          @change="changeTime"
          :editable="false"
          unlink-panels
          clearable
        />
      </el-form-item>
      <el-form-item>
        <div class="mobile-button-group horizontal">
          <el-button type="primary" icon="Search" @click="getList">查询</el-button>
          <el-button icon="Refresh" @click="reset(true)">重置</el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 移动端商品卡片视图 -->
    <div v-if="isMobile" class="mobile-card">
      <el-card v-for="item in dataList" :key="item.unique" class="product-card">
        <template #header>
          <div class="card-header">
            <span class="product-name">{{ item.product_name }}</span>
            <el-checkbox v-model="item.checked" @change="handleCardSelection(item)" />
          </div>
        </template>

        <div class="card-content">
          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.computingPower') }}:</span>
            <span class="value">{{ item.hashrate }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.warehouse') }}:</span>
            <span class="value">{{ useEnumeratePicker(warehouseList, item.wid) }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.sellableInventory') }}:</span>
            <span class="value">{{ item.quantity }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.brand') }}:</span>
            <span class="value">{{ useEnumeratePicker(brandList, item.brand) }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.type') }}:</span>
            <span class="value">{{ useEnumeratePicker(warehouseTypeList, item.is_futures) }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.arrivalDate') }}:</span>
            <span class="value">{{ item.arrival_date }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.cost') }}:</span>
            <span class="value">{{ item.original_price }}</span>
          </div>
          <div class="info-row">
            <span class="label">头程物流费:</span>
            <span class="value">{{ item.first_leg_logistics_fee }}</span>
          </div>
          <div class="info-row" v-if="form.currency">
            <span class="label">币种:</span>
            <span class="value">{{ item.actual_quoted_currency_name }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 桌面端表格视图 -->
    <div v-else class="mobile-table">
      <el-table
        class="m-t-10px"
        :data="dataList"
        highlight-current-row
        stripe
        border
        ref="tableRef"
        v-loading="tableLoading"
        row-key="unique"
        :reserve-selection="true"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :reserve-selection="true" width="55" />
        <el-table-column
          :label="t('wholesalOrder.productName')"
          prop="product_name"
          min-width="280px"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.computingPower')"
          prop="hashrate"
          :width="calculateColumnWidth('hashrate')"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.warehouse')"
          width="200px"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ useEnumeratePicker(warehouseList, row.wid) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('wholesalOrder.sellableInventory')"
          prop="quantity"
          :width="calculateColumnWidth('quantity')"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.brand')"
          min-width="200px"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ useEnumeratePicker(brandList, row.brand) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('wholesalOrder.type')"
          width="100px"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ useEnumeratePicker(warehouseTypeList, row.is_futures) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('wholesalOrder.arrivalDate')"
          prop="arrival_date"
          min-width="86px"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('order.realArrivalDate')"
          prop="real_arrival_date"
          min-width="86px"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.cost')"
          prop="original_price"
          :width="calculateColumnWidth('original_price')"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="头程物流费"
          prop="first_leg_logistics_fee"
          :width="calculateColumnWidth('first_leg_logistics_fee')"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          v-if="form.currency"
          label="币种"
          prop="actual_quoted_currency_name"
          min-width="180px"
          :show-overflow-tooltip="true"
        />
      </el-table>
    </div>

    <template #footer>
      <div class="mobile-button-group horizontal">
        <el-button class="m-r-4" @click="closeDialog"
          >{{ t('system.parameterConfig.cancel') }}
        </el-button>
        <el-button type="primary" @click="submit">{{ t('wholesalOrder.add') }}</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { useEnumeratePicker } from '@/utils'
import { getInventoryEnumApi, getInventoryListApi } from '@/api/wholesalOrder'
import { Dialog } from '@/components/Dialog'
import { ElMessage } from 'element-plus'
import { useAppStore } from '@/store/modules/app'

const emit = defineEmits(['exposeMultipleData'])
const { t } = useI18n()
const tableRef = ref()
const appStore = useAppStore()

// 移动端检测
const isMobile = computed(() => appStore.getMobile)

const isReset = ref<boolean>(false)
const dialogVisible = ref<boolean>(false)
const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const multipleSelection = ref<any[]>([])
const selectionPak = ref<any[]>([])

const paginationTotal = ref<number>(0)
const form = ref<Record<string, any>>({
  product: '',
  wid: '',
  brand: '',
  is_futures: '',
  date: [],
  start_time: '',
  end_time: '',
  type: 1,
  currency: 214
})

const warehouseList = ref<Array<Record<string, any>>>([])
const warehouseTypeList = ref<Array<Record<string, any>>>([])
const brandList = ref<Array<Record<string, any>>>([])

// 移动端卡片选择处理
const handleCardSelection = (item: any) => {
  if (item.checked) {
    if (!multipleSelection.value.some((selected) => selected.unique === item.unique)) {
      multipleSelection.value.push(item)
    }
  } else {
    multipleSelection.value = multipleSelection.value.filter(
      (selected) => selected.unique !== item.unique
    )
  }
}

//格式化时间
const changeTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.start_time = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
    form.value.end_time = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
  } else {
    form.value.start_time = null
    form.value.end_time = null
  }
}

//初始化请求
const getList = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  const resp = await getInventoryListApi(params)
  dataList.value = resp.data.list

  // 恢复选中状态
  nextTick(() => {
    if (!isMobile.value) {
      dataList.value.forEach((item) => {
        const isSelected = selectionPak.value?.some((selected) => selected.unique === item.unique)
        if (isSelected) {
          tableRef.value?.toggleRowSelection(item, true)
        }
      })
    } else if (isMobile.value) {
      dataList.value.forEach((item: Record<string, any>) => {
        item.checked =
          selectionPak.value?.some((selected) => selected.unique === item.unique) || false
      })
    }
  })

  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

//批量勾选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

//点击添加按钮
const submit = () => {
  if (isMobile.value) {
    multipleSelection.value = dataList.value.filter((item: any) => item.checked)
  }
  if (!multipleSelection.value.length) return ElMessage.warning('请勾选商品')
  emit('exposeMultipleData', multipleSelection.value)
  closeDialog()
}

//判断数组每一项指定字段是否相同
const areIdsEqual = (array: any[], key?: string) => {
  const firstId = array[0][key ?? 'id']
  return array.every((item: Record<string, any>) => item[key ?? 'id'] === firstId)
}

//一维数组去重
const deduplication = (val: any[], key?: string) => {
  if (!val || !val.length) return
  return val.reduce((acc, item) => {
    if (!acc.some((x: Record<string, any>) => x[key ?? 'id'] === item[key ?? 'id'])) {
      acc.push(item)
    }
    return acc
  }, [])
}

//重置查询项
const reset = (isRequest?: boolean) => {
  form.value = {
    product: '',
    wid: '',
    brand: '',
    is_futures: '',
    date: [],
    start_time: '',
    end_time: '',
    type: 1,
    currency: 214
  }
  isReset.value = false
  paginationTotal.value = 0
  multipleSelection.value = []
  selectionPak.value = []

  if (!isMobile.value && tableRef.value) {
    tableRef.value.clearSelection()
  }

  if (isRequest) {
    getList()
    isReset.value = true
  }
}

//点击取消关闭弹框
const closeDialog = () => {
  nextTick(() => {
    reset()
    dialogVisible.value = false
  })
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getInventoryEnumApi({ field: 'all' })
  brandList.value = resp.data.brand
  warehouseList.value = resp.data.wid
  warehouseTypeList.value = resp.data.is_futures
}

const initialize = (val: any[], currency?: number) => {
  getDropDownBoxInfo()
  form.value.currency = currency
  selectionPak.value = val || []
  multipleSelection.value = val || []

  nextTick(() => {
    getList()
  })
}

const calculateColumnWidth = (columnKey) => {
  const contentLength = getMaxContentLength(columnKey)
  return Math.min(Math.max(contentLength * 10, 100), 300) // 动态调整宽度
}

const getMaxContentLength = (columnKey) => {
  // 计算内容最大长度
  return Math.max(...dataList.value.map((item) => item[columnKey]?.length || 0))
}

defineExpose({
  dialogVisible,
  initialize
})
</script>

<style lang="less" scoped>
@media (width <= 768px) {
  .product-card {
    margin-bottom: 12px;

    .card-header {
      .product-name {
        font-size: 13px;
      }
    }

    .card-content {
      .info-row {
        margin-bottom: 6px;

        .label {
          min-width: 70px;
          font-size: 12px;
        }

        .value {
          font-size: 12px;
        }
      }
    }
  }
}

.product-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .product-name {
      margin-right: 12px;
      font-size: 14px;
      font-weight: 600;
      flex: 1;
    }
  }

  .card-content {
    .info-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      font-size: 13px;

      .label {
        min-width: 80px;
        font-weight: 500;
        color: #666;
      }

      .value {
        color: #333;
        text-align: right;
        flex: 1;
      }
    }
  }
} // 移动端商品卡片样式
</style>
